<?php 

class CUtils
{
	const LOG_NORMAL = 0;
	const LOG_WARNNING = 1;
	const LOG_ERROR = 2;
	const LOG_CRITICAL = 3;
	
	/**
	 * Get Time string
	 * @param int $time
	 * @return string
	 */
	public static function getTimeDiff($time ) 
	{
		$diff = time() - $time;
		if( $diff > 0) {
			switch ($diff) 
			{
				case($diff < 60 * 60 ) : //< 1 hours
					return round($diff / 60) . " minutes ago";
				break;
				
				case($diff < 60 * 60 * 24) : //< 1 day
					return round($diff / (60 * 60)) . " hours ago";
				break;
				
				case ( $diff < 60 * 60 * 24 * 7) : // < 7 days
					return round($diff / (60 * 60 * 24)) . " days ago";
				break;
				
				default :
					return date("Y/m/d", $time);
				break;
			}
		}
		else {
			if(abs($diff) < 60 * 60)
				return 'a second ago';
			else					
				return date("Y/m/d", $time);
		}
	}
	
	/**
	 * Return Error Message in Json format
	 * @param string $message
	 * @param boolean $encode_json
	 * @param array $data addition data
	 * @return mixed
	 */
	public static function e($message, $encode_json = true, $data = null)
	{
		// Thrown new SOAP FAIL Exception when use in web service
		if(defined('IN_SERVICE') && IN_SERVICE == 1){
			throw new SoapFault('error', Yii::t('error', $message));
			return;
		}
		
		if(!$data && !is_array($data))
		{
			$data = array();
		}
		$data['success'] = false;
		$data['message'] = Yii::t('error', $message);
		
		if($encode_json){
			return CJSON::encode($data);
		}
		return $data;
	}
	
	/**
	 * Return Success Message in Json format 
	 * @param string $message
	 * @param boolean $encode_json
	 * @param array $data
	 * @return mixed
	 */
	public static function s($message, $encode_json = true, $data = null)
	{
		if(!$data && !is_array($data))
		{
			$data = array();
		}
		$data['success'] = true;
		$data['message'] = $message;
		if($encode_json){
			return CJSON::encode($data);
		}
		return $data;
	}
	
	/**
	 * Write Log into File
	 * @param string $msg
	 */
	public static function log($msg)
	{
		$msg = "\nTime: ".date('Y-m-d H:i:s')."\n".$msg."\n\n";
		$f = fopen(self::getLogPath().'log_'.date('Ymd').'.log', 'a+');
		fwrite($f, $msg);
		fclose($f);
	}
	
	/**
	 * Get Log path
	 * @return string
	 */
	public static function getLogPath(){
		$runTimePath = Yii::getPathOfAlias("application.runtime").DIRECTORY_SEPARATOR."log/";
		if(!is_dir($runTimePath)){
			mkdir($runTimePath, 777, true);
		}
		return $runTimePath;
	}
	
	/**
	 * to byte string in MB, GB or TB
	 * @param int $byte
	 */
	public static function byteString($byte)
	{
		$str = array('byte', 'KB', 'MB', 'GB', 'TB');
		$result = '';
		if($byte < 1024)
		{
			return $byte.' byte';
		}
		$i = 1024;
		$j = 0;
		for (; $j < count($str); $i = $i * 1000, $j++)
		{
			if($byte < $i)
			{
				$result = round($byte/$i*1000, 2).' '.$str[$j];
				break;
			}
		}
		if($result == '')
		{
			$result = round($byte/$i*1000000, 2).' '.$str[$j-1];
		}
		return $result;
	}
	
	/**
	 * Get file name and remove all the /\ and file .exstension
	 * @param string $file
	 */
	public static function getFileName($file) 
	{
		$file = basename($file);
		$file = pathinfo($file);
		return $file['filename'];
	}
	
	/**
	 * Register Js Language
	 * @param array $lang
	 * @return array $lang
	 */
	public static function registerJsLang($lang)
	{
		static $slang = array();
		$slang = array_merge($slang, $lang);
		Yii::app()->getClientScript()->registerScript('Yii.'.get_class($this).'#GlobalScriptLanguage', '$lang = '.CJSON::encode($slang).';', CClientScript::POS_HEAD);
		return $slang;
	}
	
	/**
	 * js Alert
	 * @param string
	 * @param boolean
	 * @return string
	 */
	public static function jsAlert($message, $echo = false){
		$msg = "<script type='text/javascript'>malert('".str_replace("'", '"', $message)."');</script>";
		if($echo){
			echo $msg;
		}
		return $msg;
	}
		
	/**
	 * Get All language in a file
	 * @param string $filename (without extention)
	 * @return arary
	 */
	public static function getAllLangFromFile($filename) {
		$file = Yii::getPathOfAlias("application.messages").DIRECTORY_SEPARATOR.Yii::app()->language. DIRECTORY_SEPARATOR. $filename.".php";
		if(!file_exists($file) && Yii::app()->language != 'en'){
			$file = Yii::getPathOfAlias("application.messages").DIRECTORY_SEPARATOR.'en'. DIRECTORY_SEPARATOR. $filename.".php";
		}
		
		$data = include($file);
		$return = array();
		if($data)
		{
			foreach($data as $k => $v)
			{
				$k = preg_replace('/[^a-zA-Z0-9]/', '_', $k);
				$return[$k] = $v;
			}
		}
		
		return $return;
	}
	
	/**
	 * String Check Start With
	 * @param string
	 * @param string
	 * @return boolean
	 */
	public static function startsWith($haystack, $needle, $inCaseSentitive = false)
	{
	    $length = strlen($needle);
	    $found = (substr($haystack, 0, $length) === $needle);
	    if(!$found && $inCaseSentitive){
	    	return (substr(strtolower($haystack), 0, $length) === strtolower($needle));
	    }
	    return $found;
	}

	/**
	 * EndsWith
	 * @param string $haystack
	 * @param string $needle
	 * @return boolean
	 */
	public static function endsWith($haystack, $needle, $inCaseSentitive = false)
	{
	    $length = strlen($needle);
	    $start  = $length * -1; //negative
	    $found = (substr($haystack, $start) === $needle);
	    if(!$found && $inCaseSentitive){
	    	return (substr(strtolower($haystack), $start) === strtolower($needle));
	    }
	    return $found;
	}
	
	/**
	 * get Object Vars
	 * @param object $object
	 * @return array
	 */
	public static function get_object_vars($obj){
		$_arr = is_object($obj) ? get_object_vars($obj) : $obj;
		foreach ($_arr as $key => $val) {
			$val = (is_array($val) || is_object($val)) ? self::get_object_vars($val) : $val;
			$arr[$key] = $val;
		}
        return $arr;
	}
}
?>